import React, { useState, useEffect, useCallback } from "react";
import { DictTypeAPI } from "@/api/dictionary"; // 替换为实际的DictTypeAPI路径
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import {
  Plus,
  Edit,
  Trash2,
  Save,
  Search,
  MoreHorizontal,
  RefreshCw,
  AlertCircle,
  ChevronLeft,
  ChevronRight
} from "lucide-react";
import { useToast } from "@/components/ui/use-toast";

// 生成带时间戳的字典ID
const generateDictId = () => {
  return `${Date.now()}`;
};

// 字典类型管理组件
const DictionaryTypeManager = () => {
  // 状态管理
  const [dictTypes, setDictTypes] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [totalItems, setTotalItems] = useState(0);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentDict, setCurrentDict] = useState(null);
  const [formData, setFormData] = useState({
    dictName: "",
    dictType: "",
    dictId: "", // 仍保留字段但不在表单显示
    status: "0", // 默认正常
  });
  const [formErrors, setFormErrors] = useState({});
  const { toast } = useToast();

  // 计算总页数
  const totalPages = Math.ceil(totalItems / itemsPerPage) || 1;

  // 处理每页显示条数变化
  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1); // 重置到第一页
    loadDictTypes();
  };

  // 处理页码变化
  const handlePageChange = (pageNum) => {
    setCurrentPage(pageNum);
    loadDictTypes();
  };

  // 加载字典类型列表
  const loadDictTypes = useCallback(async () => {
    setIsLoading(true);
    try {
      const response = await DictTypeAPI.getList({
        page: currentPage,
        pageSize: itemsPerPage,
        searchTerm: searchTerm,
        status: statusFilter !== "all" ? statusFilter : undefined
      });
      setDictTypes(response.rows || []);
      setTotalItems(response.total || 0);
    } catch (error) {
      console.error("加载字典类型失败:", error);
      toast({
        variant: "destructive",
        title: "加载失败",
        description: "无法加载字典类型数据，请稍后重试",
      });
    } finally {
      setIsLoading(false);
    }
  }, [toast, currentPage, itemsPerPage, searchTerm, statusFilter]);

  // 初始加载
  useEffect(() => {
    loadDictTypes();
  }, [loadDictTypes]);

  // 表单数据变化处理
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    if (formErrors[name]) {
      setFormErrors((prev) => ({ ...prev, [name]: null }));
    }
  };

  // 表单验证（移除字典ID验证）
  const validateForm = () => {
    const errors = {};
    if (!formData.dictName.trim()) {
      errors.dictName = "字典名称不能为空";
    }
    if (!formData.dictType.trim()) {
      errors.dictType = "字典类型不能为空";
    }
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 打开新增模态框（自动生成字典ID）
  const handleAdd = () => {
    setCurrentDict(null);
    setFormData({
      dictName: "",
      dictType: "",
      dictId: generateDictId(), // 自动生成带时间戳的ID
      status: "0"
    });
    setFormErrors({});
    setIsModalOpen(true);
  };

  // 打开编辑模态框（保留原字典ID）
  const handleEdit = (dict) => {
    setCurrentDict(dict);
    setFormData({
      dictName: dict.dictName || "",
      dictType: dict.dictType || "",
      dictId: dict.dictId || "", // 编辑时沿用原ID
      status: dict.status?.toString() || "0",
    });
    setFormErrors({});
    setIsModalOpen(true);
  };

  // 提交表单
  const handleSubmit = async () => {
    if (!validateForm()) return;
    try {
      const submitData = { ...formData };
      if (currentDict) {
        // 编辑时保留原ID
        await DictTypeAPI.update(currentDict.dictId, {
          ...submitData,
          dict: { ...submitData.dict, dictId: currentDict.dictId },
        });
        toast({ title: "更新成功", description: "字典类型已成功更新" });
      } else {
        // 新增时使用自动生成的ID
        await DictTypeAPI.create(submitData);
        toast({ title: "创建成功", description: "新字典类型已成功创建" });
      }
      setIsModalOpen(false);
      loadDictTypes();
    } catch (error) {
      console.error("提交字典类型失败:", error);
      toast({
        variant: "destructive",
        title: "操作失败",
        description: error.message || "处理请求时发生错误，请稍后重试",
      });
    }
  };

  // 删除字典类型
  const handleDelete = async (dictId) => {
    if (!window.confirm("确定要删除此字典类型吗？删除后相关字典数据也将被移除。")) {
      return;
    }
    try {
      await DictTypeAPI.delete(dictId);
      toast({ title: "删除成功", description: "字典类型已成功删除" });
      // 处理删除最后一条数据时的页码调整
      if (dictTypes.length === 1 && currentPage > 1) {
        setCurrentPage(currentPage - 1);
      }
      loadDictTypes();
    } catch (error) {
      console.error("删除字典类型失败:", error);
      toast({
        variant: "destructive",
        title: "删除失败",
        description: error.message || "删除字典类型时发生错误，请稍后重试",
      });
    }
  };

  // 其他方法
  const handleRefresh = () => { loadDictTypes(); };
  const handleSearch = (e) => {
    if (e.key === "Enter") {
      setCurrentPage(1);
      loadDictTypes();
    }
  };
  const handleStatusChange = (value) => {
    setStatusFilter(value);
    setCurrentPage(1);
    loadDictTypes();
  };
  const renderStatusBadge = (status) => {
    switch (status) {
      case "0": return <Badge className="bg-green-100 text-green-800">正常</Badge>;
      case "1": return <Badge className="bg-red-100 text-red-800">停用</Badge>;
      default: return <Badge className="bg-gray-100 text-gray-800">未知</Badge>;
    }
  };

  // 渲染分页组件
  const renderPagination = () => {
    const startIndex = Math.max(1, (currentPage - 1) * itemsPerPage + 1);
    const endIndex = Math.min(currentPage * itemsPerPage, totalItems);
    
    if (totalItems === 0) return null;

    return (
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
        <div className="text-sm text-gray-500">
          共 {totalItems} 条数据，显示 {startIndex} 到 {endIndex} 条
        </div>
        <div className="flex items-center gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm" className="h-8 min-w-[120px]">
                每页 {itemsPerPage} 条
                <MoreHorizontal className="ml-2 h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {[5, 10, 20, 50].map((count) => (
                <DropdownMenuItem
                  key={count}
                  onClick={() => handleItemsPerPageChange(count)}
                  className={itemsPerPage === count ? "bg-primary/10" : ""}
                >
                  {count} 条/页
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
              aria-disabled={currentPage === 1}
            >
              <ChevronLeft className="h-4 w-4" />
              <span className="sr-only">上一页</span>
            </Button>
            
            {/* 生成页码 */}
            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              let pageNum;
              if (totalPages <= 5) {
                pageNum = i + 1;
              } else if (currentPage <= 3) {
                pageNum = i + 1;
              } else if (currentPage >= totalPages - 2) {
                pageNum = totalPages - 4 + i;
              } else {
                pageNum = currentPage - 2 + i;
              }
              return (
                <Button
                  key={pageNum}
                  variant={currentPage === pageNum ? "default" : "outline"}
                  size="icon"
                  className="h-8 w-8"
                  onClick={() => handlePageChange(pageNum)}
                  aria-current={currentPage === pageNum ? "page" : undefined}
                >
                  {pageNum}
                </Button>
              );
            })}
            
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages}
              aria-disabled={currentPage === totalPages}
            >
              <ChevronRight className="h-4 w-4" />
              <span className="sr-only">下一页</span>
            </Button>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="space-y-4">
      {/* 头部操作区 */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h3 className="text-lg font-semibold">字典类型管理</h3>
          <p className="text-sm text-gray-500">管理系统中所有字典的类型定义</p>
        </div>
        <div className="flex flex-wrap items-center gap-3 w-full sm:w-auto">
          <div className="relative w-full sm:w-64">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <Input
              placeholder="搜索字典名称或类型..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={handleSearch}
              className="pl-10"
            />
          </div>
          <Button
            variant="outline"
            size="icon"
            onClick={handleRefresh}
            disabled={isLoading}
          >
            <RefreshCw className={`w-4 h-4 ${isLoading ? "animate-spin" : ""}`} />
          </Button>
          <Button onClick={handleAdd}>
            <Plus className="w-4 h-4 mr-2" />
            新增字典类型
          </Button>
        </div>
      </div>

      {/* 表格区域 */}
      <div className="border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>字典名称</TableHead>
              <TableHead>字典类型</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>创建时间</TableHead>
              {/* <TableHead className="text-right">操作</TableHead> */}
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableRow>
                <TableCell colSpan={5} className="h-24 text-center">
                  <div className="flex flex-col items-center">
                    <RefreshCw className="w-6 h-6 text-gray-400 animate-spin mb-2" />
                    <span className="text-gray-500">加载中...</span>
                  </div>
                </TableCell>
              </TableRow>
            ) : dictTypes.length === 0 ? (
              <TableRow>
                <TableCell colSpan={5} className="h-24 text-center">
                  <div className="flex flex-col items-center">
                    <AlertCircle className="w-6 h-6 text-gray-400 mb-2" />
                    <span className="text-gray-500">暂无字典类型数据</span>
                    <Button variant="link" onClick={handleAdd} className="mt-1">
                      点击新增第一条数据
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ) : (
              dictTypes.map((dict) => (
                <TableRow key={dict.dictId} className="hover:bg-gray-50">
                  <TableCell>{dict.dictName}</TableCell>
                  <TableCell>{dict.dictType}</TableCell>
                  <TableCell>{renderStatusBadge(dict.status)}</TableCell>
                  <TableCell>
                    {dict.createdDate ? new Date(dict.createdDate).toLocaleString() : "-"}
                  </TableCell>
                  {/* <TableCell className="text-right">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-8 w-8">
                          <MoreHorizontal className="w-4 h-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => handleEdit(dict)}>
                          <Edit className="w-4 h-4 mr-2" />
                          编辑
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem
                          onClick={() => handleDelete(dict.dictId)}
                          className="text-red-600 focus:text-red-600"
                        >
                          <Trash2 className="w-4 h-4 mr-2" />
                          删除
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell> */}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 分页组件 */}
      {!isLoading && renderPagination()}

      {/* 新增/编辑模态框（已移除字典ID输入框） */}
      <Dialog 
        open={isModalOpen} 
        onOpenChange={() => setIsModalOpen(false)}
      >
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>
              {currentDict ? "编辑字典类型" : "新增字典类型"}
            </DialogTitle>
            <DialogDescription>
              {currentDict
                ? "修改字典类型的基本信息，字典类型用于分类管理字典数据"
                : "创建新的字典类型，用于后续管理同类字典数据"}
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            {/* 字典名称 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="dictName" className="text-right">
                字典名称 <span className="text-red-500">*</span>
              </Label>
              <Input
                id="dictName"
                name="dictName"
                value={formData.dictName}
                onChange={handleInputChange}
                className={`col-span-3 ${formErrors.dictName ? "border-red-500" : ""}`}
                placeholder="请输入字典名称"
              />
              {formErrors.dictName && (
                <p className="col-span-3 col-start-2 text-sm text-red-500 mt-1">
                  {formErrors.dictName}
                </p>
              )}
            </div>

            {/* 字典类型 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="dictType" className="text-right">
                字典类型 <span className="text-red-500">*</span>
              </Label>
              <Input
                id="dictType"
                name="dictType"
                value={formData.dictType}
                onChange={handleInputChange}
                className={`col-span-3 ${formErrors.dictType ? "border-red-500" : ""}`}
                placeholder="请输入字典类型标识"
              />
              {formErrors.dictType && (
                <p className="col-span-3 col-start-2 text-sm text-red-500 mt-1">
                  {formErrors.dictType}
                </p>
              )}
            </div>

            {/* 状态 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="status" className="text-right">
                状态
              </Label>
              <Select
                value={formData.status}
                onValueChange={(value) => setFormData((prev) => ({ ...prev, status: value }))}
              >
                <SelectTrigger className="col-span-3">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="0">正常</SelectItem>
                  <SelectItem value="1">停用</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsModalOpen(false)}>
              取消
            </Button>
            <Button onClick={handleSubmit}>
              <Save className="w-4 h-4 mr-2" />
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default DictionaryTypeManager;